package com.hbnu.system.interceptor;

import com.hbnu.system.config.BaseException;
import com.hbnu.system.model.context.BaseContext;
import io.jsonwebtoken.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.hbnu.system.utils.JwtUtils.APP_SECRET;

/**
 * jwt令牌校验的拦截器
 */
@Component
@Slf4j
public class JwtTokenUserInterceptor implements HandlerInterceptor {

    /**
     * 校验jwt
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }

        //OPTIONS请求，直接放行
        if("OPTIONS".equals(request.getMethod())){
            log.debug("OPTIONS请求，无需认证:{}", request.getRequestURI());
            return true;
        }

        try {
            //1、从请求头中获取令牌
            String token = request.getHeader("X-Token");

            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(token);

            Claims body = claimsJws.getBody();
            if(body.isEmpty()){
                throw new BaseException("认证失败");
            }
            //将用户id存入ThreadLocal
            String uid = (String) body.get("id");
            BaseContext.setCurrentId(uid);

            //放行
            return true;
        } catch (Exception e) {
            //不通过
            response.setStatus(50014);
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        BaseContext.removeCurrentId();
    }
}
